//
//  Story.swift
//  DemoUI
//
//  Created by 白瑾浩 on 2022/5/12.
//
import UIKit
import Foundation
class Music:UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate{
    
    var dpLink:CADisplayLink?
    private var  lrcs:[MusicSingLrc] = []
    var mUITableView:UITableView?
    
    var currentIndex:Int = 0//当前歌词下标
    var scrollCurrentIndex:Int = -1//当前歌词下标
    var positionImage:UILabel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .blue
        
        toLrcs()
        
        
        
        mUITableView =  UITableView(frame: CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: 500) )
        mUITableView?.backgroundColor = .gray
        self.view.addSubview( mUITableView! )
        
        self.mUITableView?.panGestureRecognizer.delaysTouchesBegan = true
        self.mUITableView?.register(NewsUITableViewCell.self, forCellReuseIdentifier: "NewsUITableViewCellId")
        
        self.mUITableView?.separatorStyle = .singleLine  //分割线
        
        //去掉左边默认的边距
        if self.mUITableView!.responds(to:Selector(("setSeparatorInset:"))){
            self.mUITableView?.separatorInset = UIEdgeInsets.zero
        }
        if self.mUITableView!.responds(to:Selector(("setLayoutMargins:"))) {
            self.mUITableView?.layoutMargins  = UIEdgeInsets.zero
        }
        self.mUITableView?.separatorInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
        
        self.mUITableView?.automaticallyAdjustsScrollIndicatorInsets = false
        self.mUITableView?.delegate = self
        self.mUITableView?.bounces = true
        self.mUITableView?.dataSource = self
        self.mUITableView?.reloadData()
        //self.mUITableView?.rowHeight = UITableView.automaticDimension
        //self.mUITableView?.estimatedRowHeight = 20 //预估高度
        
        
        
        dpLink = CADisplayLink(target: self, selector: #selector(self.update))
        dpLink?.frameInterval = 5 /////每5帧处理一次 大概 一秒60/5次
        dpLink?.isPaused = false //true 是否暂停
        dpLink?.add(to: RunLoop.current, forMode: .common)
        
        
        
        positionImage = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
        positionImage?.text = "位置"
        positionImage?.backgroundColor = .green
        positionImage?.textColor = .white
        self.view.addSubview( positionImage! )
        positionImage?.snp.makeConstraints({ make in
            make.right.equalToSuperview()
            make.height.equalTo( 30 )
            make.width.equalTo( 100 )
            make.top.equalTo( 100 + 500*0.5 )
        })
        
        
    }
    func setCurrentTime( _ currentTime:Float ){
        //手指在滚动 返回暂不处理
        if isScroll {
            return
        }
        
        for index in 0..<lrcs.count{
            let lrc = lrcs[index]
            
            print( "lrc===currentTime=\(currentTime);total=\( lrc.time + lrc.continuousTime )" )
            
            if currentIndex != index  && currentTime >= lrc.time && currentTime <= (lrc.time + lrc.continuousTime){
                
                let indexPath = IndexPath(row: index, section: 0)
                
                //             let preindexPath = IndexPath(row: currentIndex, section: 0)
                
                //self.mUITableView?.reloadRows(at: [preindexPath,indexPath], with: UITableView.RowAnimation.none)
                
                //                print( "currentIndex***=\(index)" )
                //                print( "precurrentIndex***=\(currentIndex)" )
                //
                //  self.mUITableView?.reloadData()
                // self.mUITableView?.layoutIfNeeded()
                
                print( "lrc===\(lrc.lrc)=\(index)=currentIndex=\(currentIndex)" )
                
                currentIndex = index
                
                self.mUITableView?.reloadData()
                
                self.mUITableView?.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.top, animated: true )
                
                
                
            }
            
            //            if currentIndex == index {
            //
            //
            //
            //
            //                let  process =  currentTime
            //
            //                let indexPath = IndexPath(row: index, section: 0)
            //
            //                let cellobject = self.mUITableView?.cellForRow(at: indexPath)
            //                if cellobject != nil{
            //                    let cell =  cellobject as! NewsUITableViewCell
            //
            //                    cell.subtitle.progress = process
            //                }
            //
            //            }
            //
            
        }
        
        
    }
    
    var ii = 0
    var jj = 0
    
    @objc func update(){
        
        
        if ii > 20 {
            ii  = 0
            jj = jj+1
            if jj >= lrcs.count {
                jj = 0
            }
            let currentTime = lrcs[jj].continuousTime * Float(ii) / 20   + lrcs[jj].time
            
            setCurrentTime( currentTime )
        }
        
        
        
        
        ii = ii + 1
        
    }
    func startDpLink(){
        //self.dpLink.paused = false
    }
    func stopDpLink(){
        //self.pdpLink.invalidate()
    }
    override func viewWillLayoutSubviews() {
        self.mUITableView?.contentInset = UIEdgeInsets(
            top: (self.mUITableView?.bounds.size.height)! * 0.5,
            left: 0,
            bottom: (self.mUITableView?.bounds.size.height)! * 0.5,
            right: 0)
    }
    var isScroll:Bool  = false
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let first = self.mUITableView?.visibleCells.first
        guard let first = first else{
            return
        }
        let firstIndex = self.mUITableView?.indexPath(for: first)
        print( "scrollViewDidScroll滚动中,头部索引=\(firstIndex!.row)" )
        
        let cellframe = first.frame
        
        let tableViewOffsetY = self.mUITableView?.contentOffset.y
        
        print( "scrollViewDidScroll滚动中,tableViewOffsetY=\(tableViewOffsetY)" )
        
        
        print( "scrollViewDidScroll滚动中,cellframeY=\(cellframe.origin.y )" )
        
        print( "scrollViewDidScroll滚动中,cellframeY2=\(CGFloat(cellframe.origin.y)-CGFloat(tableViewOffsetY!) )" )
        
        
        let firstY = CGFloat(cellframe.origin.y)-CGFloat(tableViewOffsetY!)
        
        
        if firstY <= 0 {
            
            
            //计算一般能显示几个item
            let pageNum  = 250/30
            
            
            //print( "scrollViewDidScroll滚动中，滚动高度=\(self.mUITableView?.scrollsToTop)" )
            
            scrollCurrentIndex = firstIndex!.row+pageNum
            
            
        }else{
            
            let pageNum = ( 250 - firstY )/30
            
            
            scrollCurrentIndex = Int(pageNum)
        }
        
        guard scrollCurrentIndex < lrcs.count else {
            scrollCurrentIndex = lrcs.count - 1
            self.mUITableView?.reloadData()
            return
        }
        print( "scrollViewDidScroll滚动中scrollCurrentIndex=\(scrollCurrentIndex)===\(lrcs[scrollCurrentIndex].lrc)" )
        
        self.mUITableView?.reloadData()
        
        
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print( "scrollViewWillBeginDragging滚动开始" )
        isScroll  = true
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        print( "scrollViewDidEndDragging滚动结束==\(decelerate)" )
        //self.mUITableView?.get
        if !decelerate{
            
            
            
            //等2s中恢复自动滚动
            DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
                self.isScroll  = false
                self.scrollCurrentIndex = -1
            }
            
        }
    }
    // 设置tableView每行的预估高度
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 30
    }
    // 设置tableView每行的高度自适应
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 30//UITableView.automaticDimension
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return lrcs.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NewsUITableViewCellId", for: indexPath) as! NewsUITableViewCell
        print( "currentIndex=\(currentIndex)===scrollCurrentIndex=\(scrollCurrentIndex)=====\(indexPath.row)" )
        cell.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 20)
        if currentIndex == indexPath.row{
            
            cell.subtitle.font = UIFont.systemFont(ofSize:  20 )
            
        }else{
            cell.subtitle.font = UIFont.systemFont(ofSize:  14 )
            
        }
        
        //是否手动滚动
        if scrollCurrentIndex == indexPath.row && isScroll{
            
            cell.subtitle.textColor = .red
            
        }else{
            cell.subtitle.textColor = .blue
            
        }
        
        
        let news = lrcs[indexPath.row]
        
        cell.subtitle.text = news.lrc
        
        return cell
    }
    
    
    //歌词文件转数据
    func toLrcs(){
        let settingsBundlePath = Bundle.main.path(forResource:"Settings", ofType:"bundle")
        
        let path = Bundle.init(path: settingsBundlePath! )
        //print( "path\(path)" )
        let path2 = path?.path(forResource:"lrc", ofType:"lrc", inDirectory:"") //目录
        
        let lrcContent  = try? String(contentsOfFile: path2!, encoding: String.Encoding.utf8)
        
        if lrcContent == nil {
            return
        }
        let lrcContentArr:[String] = lrcContent!.components(separatedBy: .newlines)
        //计算每一行歌词持续时间
        var upLrcIndex = -1
        for index in 0..<lrcContentArr.count{
            let mMusicSingLrc = MusicSingLrc()
            let item = lrcContentArr[index]
            //            1、ti：在歌词中的含义是：歌曲标题。
            //            2、ar：在歌词中的含义是：歌手姓名，若信息不详可以注明“未知”或“none”。
            //            3、al：在歌词中的含义是：专辑名称(电视剧主题曲等注明电视剧名称)。
            //            4、by：歌词编辑者
            //            5、offset 偏移量
            if item.contains( "ti" ) || item.contains( "ar" ) || item.contains( "al" ) || item.contains( "by" ) || item.contains( "offset" ) {
                continue
            }
            let aStrArr = item.split(separator: "]")
            if aStrArr.count <= 0  {
                continue
            }
            let timeStrArr = aStrArr[0].split(separator:  ":" )
            if timeStrArr.count <= 0 {
                continue
            }
            //- 0 : "[00"
            //- 1 : "10.40"
            let minutes = timeStrArr[0].replacingOccurrences(of: "[", with: "")
            let totalTime = Float( minutes  )! * 60 + Float(timeStrArr[1])!
            
            mMusicSingLrc.lrc = aStrArr.count>1 ? String(aStrArr[1]) : ""
            mMusicSingLrc.time = totalTime
            mMusicSingLrc.timeStr = "\(minutes):\(timeStrArr[1])"
            if upLrcIndex >= 0 {
                let  lrcsItem = lrcs[upLrcIndex]
                lrcsItem.continuousTime = mMusicSingLrc.time - lrcsItem.time
            }
            upLrcIndex = upLrcIndex + 1 //保存当前索引，利用下一句歌词时间来 计算此索引歌词持续时间， 最后一句歌词用 歌曲的总时间来计算
            lrcs.append( mMusicSingLrc )
        }
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        dpLink?.invalidate()
    }
    
    
    
    
    
}

class MusicSingLrc{
    var lrc:String = ""
    var time:Float = 0 //当前时间
    var timeStr:String = ""
    var continuousTime:Float = 0 //持续时间
}


class NewsUITableViewCell:UITableViewCell{
    
    lazy var subtitle:CLLrcLabel = {
        let lbl = CLLrcLabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 30))
        lbl.numberOfLines = 1
        lbl.backgroundColor = .red
        lbl.textAlignment = .left
        lbl.font = UIFont.boldSystemFont(ofSize:  16)
        lbl.textColor = UIColor.blue
        lbl.progress = 0.0
        return lbl
    }()
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = UITableViewCell.SelectionStyle.none
        
        self.contentView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 30)
        self.backgroundColor = .blue
        //addSubview(backView)
        self.backgroundColor = .white
        
        self.contentView.addSubview(subtitle)
        
        subtitle.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.height.equalTo( 30 )
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        self.selectionStyle = .none  //取消选中样式
        
        
    }
}

class CLLrcLabel:UILabel{
    var progress:Float = 0.0
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        UIColor.green.set()
        let fillRect = CGRect(x: 0, y: 0, width: self.bounds.size.width * CGFloat(progress), height: self.bounds.size.height)
        UIRectFillUsingBlendMode(fillRect, CGBlendMode.sourceIn)
    }
    
}
